import { createApp } from 'vue'
import { createPinia } from 'pinia'

import App from './App.vue'
import router from './router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
const app = createApp(App)
export { app }
//directive 是 Vue.js 中的一个内置方法，用于注册自定义指令。创建一个名为 longpress 的自定义指令。
app.directive('longpress', {
  mounted: function (el, binding, vNode) {
    // Make sure expression provided is a function
    if (typeof binding.value !== 'function' && vNode.context !== undefined) {
      // pass warning to console
      let warn = `[longpress:] provided expression '${binding.expression}' is not a function, but has to be`
      console.warn(warn)
    }

    // Define variable
    let pressTimer = null

    // 鼠标按下就开始执行
    //   e instanceof MouseEvent：检查事件对象是否是鼠标事件。
    // e.type === "click"：检查事件的类型是否为点击。
    // e.button !== 0：检查点击的鼠标按钮是否是主按钮（通常是左键）。
    let start = (e) => {
      if (e instanceof MouseEvent && e.type === 'click' && e.button !== 0) {
        return
      }
      handler(e)
    }

    // Cancel Timeout
    let cancel = () => {
      // Check if timer has a value or not
      if (pressTimer !== null) {
        clearTimeout(pressTimer)
        pressTimer = null
      }
    }
    // Run Function
    //递归函数  (函数自身调用自身)
    // 一定要加定时器，否则执行速度很快。定时器注销后，递归也随之结束
    const handler = (e) => {
      pressTimer = setTimeout(() => {
        binding.value(e)
        handler(e)
      }, 60)
    }

    // Add Event listeners
    el.addEventListener('mousedown', start)
    // Cancel timeouts if this events happen
    el.addEventListener('click', cancel)
    el.addEventListener('mouseup', cancel)
    el.addEventListener('mouseout', cancel)
  }
})
app.use(createPinia())
app.use(router)
app.use(ElementPlus)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

app.mount('#app')
